import { NotFound, Forbidden, log } from 'lin-mizar';
import Sequelize from 'sequelize';
import { Content } from '../model/content';

class ContentDao {
  async getContent (id) {
    const content = await Content.findOne({
      where: {
        id
      }
    });
    return content;
  }

  async getContentByKeyword (q) {
    const content = await Content.findOne({
      where: {
        title: {
          [Sequelize.Op.like]: `%${q}%`
        }
      }
    });
    return content;
  }

  async getContents () {
    const contents = await Content.findAll();
    return contents;
  }

  async createContent (v) {
    const content = await Content.findOne({
      where: {
        title: v.get('body.title')
      }
    });
    if (content) {
      throw new Forbidden({
        code: 10240,
        message: '同名文章，请勿重复发布！'
      });
    }
    const ct = new Content();
    // 暂未做严格的参数校验
    ct.title = v.get('body.title');
    ct.keywords = v.get('body.keywords');
    ct.description = v.get('body.description');
    ct.cover = v.get('body.cover');
    await ct.save();
  }

  async updateContent (v, id) {
    const content = await Content.findByPk(id);
    if (!content) {
      throw new NotFound({
        code: 10022
      });
    }
    content.title = v.get('body.title');
    content.keywords = v.get('body.keywords');
    content.description = v.get('body.description');
    content.cover = v.get('body.cover');
    await content.save();
  }

  async deleteContent (id) {
    const content = await Content.findOne({
      where: {
        id
      }
    });
    if (!content) {
      throw new NotFound({
        code: 10022
      });
    }
    content.destroy();
  }
}

export { ContentDao };
